<?php

/**
 * 获取所有模块Service
 * @param string $name 指定service名
 * @return array
 */
function get_all_service($name, $method, $vars = array()) {
    if (empty($name)) return null;
    $apiPath = APP_PATH . '*/service/' . $name . 'Service.php';
    $apiList = glob($apiPath);
    if (empty($apiList)) {
        return;
    }
    $appPathStr = strlen(APP_PATH);
    $method = 'get' . $method . $name;
    $data = array();
    foreach ($apiList as $value) {
        $path = substr($value, $appPathStr, -4);
        $path = str_replace('\\', '/', $path);
        $appName = explode('/', $path);
        $appName = $appName[0];
        $config = load_config($appName . '/config');
        if (!$config['APP_SYSTEM'] && (!$config['APP_STATE'] || !$config['APP_INSTALL'])) {
            continue;
        }
        $class = '\\app\\' . $appName . '\\' . 'service' . '\\' . $name . 'Service';
        if (!class_exists($class)) {
            return;
        }
        $class = target($appName . '/' . $name, 'service');
        if (method_exists($class, $method)) {
            $data[$appName] = $class->$method($vars);
        }
    }
    return $data;
}

/**
 * 获取指定模块Service
 * @param string $name 指定service名
 * @return Service
 */
function service($appName, $name, $method, $vars = array()) {
    $config = load_config($appName . '/config');
    if (!$config['APP_SYSTEM'] && (!$config['APP_STATE'] || !$config['APP_INSTALL'])) {
        return;
    }
    $class = '\\app\\' . $appName . '\\' . 'service' . '\\' . $name . 'Service';
    if (!class_exists($class)) {
        return;
    }
    $class = target($appName . '/' . $name, 'service');
    if (method_exists($class, $method)) {
        return $class->$method($vars);
    }
}

/**
 * 调用指定模块的API
 * @param string $name 指定api名
 * @return Api
 */
function api($appName, $name, $method, $vars = array()) {
    $config = load_config($appName . '/config');
    if (!$config['APP_SYSTEM'] && (!$config['APP_STATE'] || !$config['APP_INSTALL'])) {
        return;
    }
    $class = '\\app\\' . $appName . '\\' . 'api' . '\\' . $name . 'Api';
    if (!class_exists($class)) {
        return;
    }
    $class = target($appName . '/' . $name, 'api');
    if (method_exists($class, $method)) {
        return $class->$method($vars);
    }
}


/**
 * 读取配置文件
 * @param string $file 调用文件
 * @return array
 */
function load_config($file) {
    $file = get_config_file($file);
    return require $file;
}

/**
 * 解析配置文件路径
 * @param string $file 文件路径或简写路径
 * @return dir
 */
function get_config_file($file) {
    $name = $file;
    if (!is_file($file)) {
        $str = explode('/', $file);
        $strCount = count($str);
        switch ($strCount) {
            case 1:
                $app = APP_NAME;
                $name = $str[0];
                break;
            case 2:
                $app = $str[0];
                $name = $str[1];
                break;
        }
        $app = strtolower($app);
        if (empty($app) && empty($file)) {
            throw new \Exception("Config '{$file}' not found", 500);
        }
        $file = APP_PATH . "{$app}/conf/{$name}.php";
        if (!file_exists($file)) {
            throw new \Exception("Config '{$file}' not found", 500);
        }
    }
    return $file;
}

/**
 * URL生成
 */
function url($route = null, $params = array()){
    return \variant\core\Route::url($route, $params);
}

/**
 * 获取request请求方法
 */
function request($str = null, $default = null, $function = null) {
    static $args;
    $str = trim($str);
    list($method,$name) = explode('.',$str,2);
    $method = strtoupper($method);
    if($method == 'POST') {
        $args = $_POST;
    } elseif($method == 'GET') {
        $args = $_GET;
    } elseif($method == 'REQUEST') {
        $args = $_REQUEST;
    }else{
        $name = $str;
        $args = array_merge((array)$_GET, (array)$_POST);
    }
    if(empty($name)){
        return filterData($args);
    }else{
        if($method == 'GET'){
            $data = urldecode($args[$name]);
        }else{
            $data = $args[$name];
        }
        $data = filterData($data);
        if($function){
            $data = call_user_func($function,$data);
        }
        if(empty($data)){
            $data = $default;
        }
        return $data;
    }
}

/**
 * 循环过滤数组
 * @param  array $data 过滤内容
 */
function filterData($data) {
    if (is_array($data)){
        foreach ($data as $k=>$v){
            $data[$k] = filterData($v);
        }
        return $data;
    }else{
        return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    }
}

/**
 * 通用模块调用函数
 * @param string $class 调用路径
 * @param string $layer 调用层 默认model
 * @return obj
 */
function target($class, $layer = 'model'){
	static $objArr = array();
	$param = explode('/', $class, 2);
	$paramCount = count($param);
	switch ($paramCount) {
		case 1:
			$app = APP_NAME;
			$module = $param[0];
			break;
		case 2:
			$app = $param[0];
			$module = $param[1];
			break;
	}
    $module = ucfirst($module);
	$app = strtolower($app);
	$class = "\\app\\{$app}\\{$layer}\\{$module}".ucfirst($layer);
	if(isset($objArr[$class])){
        return $objArr[$class];
	}
	if(!class_exists($class)){
		throw new \Exception("Class '{$class}' not found'", 500);
	}
	$obj = new $class();
	$objArr[$class] = $obj;
	return $obj;
}

/**
 * 二维数组排序
 * @param array $array 排序的数组
 * @param string $key 排序主键
 * @param string $type 排序类型 asc|desc
 * @param bool $reset 是否返回原始主键
 * @return array
 */
function array_order($array, $key, $type = 'asc', $reset = false) {
    if (empty($array) || !is_array($array)) {
        return $array;
    }
    foreach ($array as $k => $v) {
        $keysvalue[$k] = $v[$key];
    }
    if ($type == 'asc') {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    $i = 0;
    foreach ($keysvalue as $k => $v) {
        $i++;
        if ($reset) {
            $new_array[$k] = $array[$k];
        } else {
            $new_array[$i] = $array[$k];
        }
    }
    return $new_array;
}


/**
 * session获取
 * @param string $name
 * @param string $value
 * @return  string
 */
function session($name='',$value = '') {
	if(empty($name)){
		return $_SESSION;
	}
    $sessionId = request('request.session_id');
    if(!empty($sessionId)){
        session_id($sessionId);
    }
	if(!isset($_SESSION)){
        session_start();
    }
	$pre = config('COOKIE_PREFIX');
	if($value === ''){
		$session = $_SESSION[$pre . $name];
	}else{
		$session = $_SESSION[$pre . $name] = $value;
	}
	return $session;
}

/**
 * session卸载
 */
function unset_session($name) {
    $pre = config('COOKIE_PREFIX');
    unset($_SESSION[$pre . $name]);
}

/**
 * cookie获取
 * @param string $name
 * @param string $value
 * @param int $time 小时时间
 * @return  string
 */
function cookie($name='',$value='',$time = 1) {
    if(empty($name)){
        return $_COOKIE;
    }
    $pre = config('COOKIE_PREFIX');
    if($value === ''){
        $cookie = $_COOKIE[$pre . $name];
    }else{
        $cookie = setcookie($pre . $name, $value, time()+3600*$time, '/');
    }
    return $cookie;
}

/**
 * 获取文件或文件大小
 * @param string $directoty 路径
 * @return int
 */
function dir_size($directoty) {
    $dir_size = 0;
    if ($dir_handle = @opendir($directoty)) {
        while ($filename = readdir($dir_handle)) {
            $subFile = $directoty . DIRECTORY_SEPARATOR . $filename;
            if ($filename == '.' || $filename == '..') {
                continue;
            } elseif (is_dir($subFile)) {
                $dir_size += dir_size($subFile);
            } elseif (is_file($subFile)) {
                $dir_size += filesize($subFile);
            }
        }
        closedir($dir_handle);
    }
    return ($dir_size);
}

//复制目录
function copy_dir($sourceDir,$aimDir) {
    $succeed = true;
    if(!file_exists($aimDir)){
        if(!mkdir($aimDir,0777)){
            return false;
        }
    }
    $objDir = opendir($sourceDir);
    while(false !== ($fileName = readdir($objDir))){
        if(($fileName != ".") && ($fileName != "..")){
            if(!is_dir("$sourceDir/$fileName")){
                if(!copy("$sourceDir/$fileName","$aimDir/$fileName")){
                    $succeed = false;
                    break;
                }
            }
            else{
                copy_dir("$sourceDir/$fileName","$aimDir/$fileName");
            }
        }
    }
    closedir($objDir);
    return $succeed;
}

/**
 * 遍历删除目录和目录下所有文件
 * @param string $dir 路径
 * @return bool
 */
function del_dir($dir) {
    if (!is_dir($dir)){
		return false;
	}
	$handle = opendir($dir);
	while (($file = readdir($handle)) !== false){
		if ($file != "." && $file != ".."){
			is_dir("$dir/$file")? del_dir("$dir/$file") : @unlink("$dir/$file");
		}
	}
	if (readdir($handle) == false){
		closedir($handle);
		@rmdir($dir);
	}
}

/**
 * html代码还原
 */
function html_out($str){
    if(function_exists('htmlspecialchars_decode')){
        $str=htmlspecialchars_decode($str);
    }else{
        $str=html_entity_decode($str);
    }
    $str = stripslashes($str);
    return $str;
}

/**
 * html代码清理
 */
function html_clear($str){
    $str = html_out($str);
    return strip_tags($str);
}

/**
 * XSS过滤
 */
function html_xss($data, $allowedTags = array(), $allowedStyleProperties = array()) {
	static $xss;
	if(!isset($xss)) {
		$xss = new \variant\ext\Xss();
	}
	$html = $this->html_out($data);
	return $xss->filter($html, $allowedTags, $allowedStyleProperties);
}

/**
 * 字符串截取
 */
function str_len($str, $length, $charset="utf-8", $suffix = true) {
    if($charset!='utf-8'){
        $str = mb_convert_encoding($str,'utf8',$charset);
    }
    $osLen = mb_strlen($str);
    if($osLen <= $length){
        return $str;
    }
    $string = mb_substr($str,0,$length,'utf8');
    $sLen = mb_strlen($string,'utf8');
    $bLen = strlen($string);
    $sCharCount = (3*$sLen-$bLen)/2;
    if($osLen<=$sCharCount+$length){
        $arr = preg_split('/(?<!^)(?!$)/u',mb_substr($str,$length+1,$osLen,'utf8')); //将中英混合字符串分割成数组（UTF8下有效）
    }else {
        $arr = preg_split('/(?<!^)(?!$)/u',mb_substr($str,$length+1,$sCharCount,'utf8'));
    }
    foreach($arr as $value){
        if(ord($value)<128 && ord($value)>0){
            $sCharCount = $sCharCount-1;
        }else {
            $sCharCount = $sCharCount-2;
        }
        if($sCharCount<=0){
            break;
        }
        $string.=$value;
    }
    //return $string;
	if($suffix) return $string;
	return $string;
}

/**
 * 获取客户端IP
 */
function get_client_ip()
{
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
		   $ip = getenv("HTTP_CLIENT_IP");
	   else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
		   $ip = getenv("HTTP_X_FORWARDED_FOR");
	   else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
		   $ip = getenv("REMOTE_ADDR");
	   else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
		   $ip = $_SERVER['REMOTE_ADDR'];
	   else
		   $ip = "unknown";
	   return $ip;
}

/**
 * 默认数据
 * @param string $data
 * @param string $var
 * @return  string
 */
function default_data($data,$var){
    if(empty($data)){
        return $var;
    }else{
        return $data;
    }
}

/**
 * 判断不为空
 */
function is_empty($str)
{
    if(empty($str)){
        return false;
    }else{
        return true;
    }
}

/**
 * 判断UTF-8
 * @param  string  $string 字符串
 * @return boolean
 */
function is_utf8($string){
	if( !empty($string) ) {
		$ret = json_encode( array('code'=>$string) );
		if( $ret=='{"code":null}') {
			return false;
		}
	}
	return true;
}

/**
 * 字符串转码
 * @param  string $fContents 字符串
 * @param  string $from      原始编码
 * @param  string $to        目标编码
 * @return string
 */
function auto_charset($fContents,$from='gbk',$to='utf-8'){
	$from   =  strtoupper($from)=='UTF8'? 'utf-8':$from;
	$to       =  strtoupper($to)=='UTF8'? 'utf-8':$to;
	if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){
		//如果编码相同或者非字符串标量则不转换
		return $fContents;
	}
	if(is_string($fContents) ) {
		if(function_exists('mb_convert_encoding')){
			return mb_convert_encoding ($fContents, $to, $from);
		}elseif(function_exists('iconv')){
			return iconv($from,$to,$fContents);
		}else{
			return $fContents;
		}
	}
	elseif(is_array($fContents)){
		foreach ( $fContents as $key => $val ) {
			$_key =     self::auto_charset($key,$from,$to);
			$fContents[$_key] = self::auto_charset($val,$from,$to);
			if($key != $_key )
				unset($fContents[$key]);
		}
		return $fContents;
	}
	else{
		return $fContents;
	}
}

/**
 * 生成唯一数字
 */
function unique_number() {
    return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * 生成随机字符串
 */
function random_str() {
    $year_code = array('A','B','C','D','E','F','G','H','I','J');
    $order_sn = $year_code[intval(date('Y'))-2010].
    strtoupper(dechex(date('m'))).date('d').
    substr(time(),-5).substr(microtime(),2,5).sprintf('d',rand(0,99));
    return $order_sn;
}

